package com.hermes.comics.extractors;

import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hermes.comics.data.Issue;
import com.hermes.comics.data.IssueTag;
import com.hermes.comics.data.Serie;
import com.hermes.comics.data.SerieTag;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class GuiaDosQuadrinhosExtractor extends WebExtractor {

  private static final Pattern TITLE_PATTERN = Pattern.compile(
      "<h1 ><span id=\"nome_titulo_lb\">(.*?)<nobr>", Pattern.DOTALL);

  private static final Pattern NUMBER_PATTERN = Pattern.compile(
      "<div id='d0' class=\"details\">.*?<strong>(\\d+)</strong>.*?</div>", Pattern.DOTALL);

  private static final Pattern[] AUTHOR_PATTERNS = {
      Pattern.compile("<strong>Texto: </strong>\\s*<a href=\".*?\">(.*?)</a>", Pattern.DOTALL),
      Pattern.compile("<strong>Desenho: </strong>\\s*<a href=\".*?\">(.*?)</a>", Pattern.DOTALL),
      Pattern.compile("<strong>Roteiro: </strong>\\s*<a href=\".*?\">(.*?)</a>", Pattern.DOTALL),
      Pattern.compile("<strong>Arte: </strong>\\s*<a href=\".*?\">(.*?)</a>", Pattern.DOTALL),
      Pattern.compile("<strong>História: </strong>\\s*<a href=\".*?\">(.*?)</a>", Pattern.DOTALL)
  };

  private static final Pattern FORMAT_PATTERN = Pattern.compile(
      "<span id=\"formato\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern PAGES_PATTERN = Pattern.compile(
      "<span id=\"paginas\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern PUBLISHER_PATTERN = Pattern.compile(
      "<a id=\"editora_link\" href=\".*?\">(.*?)</a>", Pattern.DOTALL);

  private static final Pattern CATEGORY_PATTERN = Pattern.compile(
      "<span id=\"categoria\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern GENRE_PATTERN = Pattern.compile(
      "<span id=\"genero\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern STATUS_PATTERN = Pattern.compile(
      "<span id=\"status\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern LICENSER_PATTERN = Pattern.compile(
      "<span id=\"licenciador\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern DATE_PATTERN = Pattern.compile(
      "<span id=\"data_publi\">(.*?)</span>", Pattern.DOTALL);

  private static final Pattern IMAGE_PATTERN = Pattern.compile(
      "<img src=\".*?(ShowImage.*?path=.*?jpg)\"", Pattern.DOTALL); 

  private static final Pattern SUBTITLE_PATTERN = Pattern.compile(
      "<span id=\"descricao\">(.*?)<br/></span>", Pattern.DOTALL);
  
  private static final Pattern KEY_PATTERN = Pattern.compile(
      "cod_tit=(.*?)\\+?\\&", Pattern.DOTALL);

  private static final Pattern URL_PATTERN = Pattern.compile(
      "<script src=\"/(edicao/.*?)\\?.*?\"", Pattern.DOTALL);

  // ------------------------------------------------------------------

  private static final Pattern URLS_PATTERN = Pattern.compile(
      "<a href=\"(edicao\\.aspx.*?)\">\\d+</a>", Pattern.DOTALL);

  private static final String BASE_URL = "http://www.guiadosquadrinhos.com/";
  private static final String BASE_THUMB_IMG = BASE_URL + "capasthumbs/antigas/";

  public GuiaDosQuadrinhosExtractor(String url, String content) {
    super(url, content);
  }

  @Override
  public List<String> extractUrls() {
    List<String> urls = new ArrayList<String>();
    urls.add(getUrl());

    Matcher matcher = URLS_PATTERN.matcher(getContent());
    while (matcher.find()) {
      urls.add(BASE_URL + matcher.group(1).replace("&amp;", "&"));
    }
    Collections.sort(urls);

    return urls;
  }

  private Set<String> extractPublishers() {
    Set<String> result = new HashSet<String>();
    String match = match(getContent(), PUBLISHER_PATTERN)
        .replace("N/A", "")
        .replace("DC (Vertigo)", "DC Comics/Vertigo");
    if (!TextUtils.isEmpty(match)) {
      for (String part : match.split("/")) {
        result.add(part.trim());
      }
    }

    match = match(getContent(), LICENSER_PATTERN)
        .replace("N/A", "")
        .replace("sem licenciador", "")
        .replace("DC (Vertigo)", "DC Comics/Vertigo");
    if (!TextUtils.isEmpty(match)) {
      for (String part : match.split("/")) {
        result.add(part.trim());
      }
    }
    return result;
  }

  private Set<String> extractAuthors() {
    Set<String> result = new HashSet<String>();

    for (Pattern pattern : AUTHOR_PATTERNS) {
      String match = match(getContent(), pattern);
      if (!TextUtils.isEmpty(match)) {
        result.add(match);
      }
    }

    return result;
  }

  @Override
  public boolean extractSerie(Serie serie) {
    serie.setTag(SerieTag.KEY, match(getContent(), KEY_PATTERN));
    if (TextUtils.isEmpty(SerieTag.KEY.value(serie))) {
      return false;
    }

    serie.setTag(SerieTag.TITLE, match(getContent(), TITLE_PATTERN));

    serie.setTag(SerieTag.CATEGORY, match(getContent(), CATEGORY_PATTERN) + "|" + match(getContent(), STATUS_PATTERN));

    Set<String> publishers = extractPublishers();
    Set<String> authors = extractAuthors();

    for (String author : authors) {
      if (publishers.contains(author)) {
        publishers.remove(author);
      }
    }

    serie.setTag(SerieTag.PUBLISHER, TextUtils.join("|", publishers));
    serie.setTag(SerieTag.AUTHOR, TextUtils.join("|", authors));

    String match = match(getContent(), FORMAT_PATTERN);

    Set<String> formats = new HashSet<String>();
    for (String parts : match.split("(<br/?>)|/")) {
      String newPart = parts.replaceAll("\\(.*?\\)", "").trim();
      if (!TextUtils.isEmpty(newPart)) {
        formats.add(newPart);
      }
    }
    serie.setTag(SerieTag.FORMAT, TextUtils.join("|", formats));

    serie.setTag(SerieTag.LANGUAGE, "pt");
    serie.setTag(SerieTag.GENRE, match(getContent(), GENRE_PATTERN));

    System.out.println(serie.verbose());

    return true;
  }

  @Override
  public String getUrl() {
    return BASE_URL + match(getContent(), URL_PATTERN);
  }

  @Override
  public boolean extractIssue(Issue issue) {
    String key = match(getContent(), NUMBER_PATTERN);
    if (TextUtils.isEmpty(key)) {
      key = "1";
    }
    issue.setTag(IssueTag.KEY, key);

    issue.setTag(IssueTag.SERIE_KEY, match(getContent(), KEY_PATTERN));
    if (TextUtils.isEmpty(IssueTag.SERIE_KEY.value(issue))) {
      return false;
    }

    issue.setTag(IssueTag.PAGES, match(getContent(), PAGES_PATTERN));
    issue.setTag(IssueTag.DATE, match(getContent(), DATE_PATTERN));
    issue.setTag(IssueTag.TITLE, match(getContent(), SUBTITLE_PATTERN));
    issue.setTag(IssueTag.URL, getUrl());

    String val = match(getContent(), IMAGE_PATTERN);
    if (val != null) {
      issue.setTag(IssueTag.IMG, BASE_URL + "edicao/" + val + "&w=400&h=514");
    }

    System.out.println(issue.verbose());

    return true;
  }
}
